package com.xinggq.pay.service.pay.channel.yse.other.division;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson2.JSONObject;
import com.xinggq.pay.service.pay.channel.yse.other.division.dto.DivisionParamDTO;
import com.xinggq.pay.service.entity.YsePayConfigEntity;
import com.xinggq.pay.service.adaptor.YseApiAdaptor;
import com.xinggq.pay.service.pay.channel.yse.enums.YseMethodEnum;
import com.xinggq.pay.service.pay.channel.yse.other.division.dto.DivisionReqDTO;
import com.xinggq.pay.service.pay.channel.yse.other.division.dto.DivisionRespDTO;
import com.xinggq.pay.service.pay.channel.yse.utils.YseUtil;
import com.xinggq.pay.service.service.YsePayConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 银盛分账接口
 * @Description
 * @Author xinggq
 * @Date 2025/9/12
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class YseDivisionServiceImpl{

  private final YseApiAdaptor yseApiAdaptor;
  private final YsePayConfigService ysePayConfigService;


  /**
   * 异步进行分账登记
   * @param payParamDto
   * @return
   */
  @Async("taskExecutor")
  public void divisionAsync(DivisionParamDTO payParamDto) {
    try {
      DivisionRespDTO division = division(payParamDto);
      log.info("分账登记返回结果：{}",JSONObject.toJSONString( division));
      if(!division.isSuccess()){
        log.error("异步分账登记失败，渠道订单号：{}",
            payParamDto != null ? payParamDto.getChannelOutTradeNo() : "未知");
      }
    } catch (Exception e) {
      log.error("异步分账登记失败，渠道订单号：{}",
          payParamDto != null ? payParamDto.getChannelOutTradeNo() : "未知", e);
    }
  }

  public DivisionRespDTO division(DivisionParamDTO payParamDto) {
    Validator.validateNotNull(payParamDto, "银盛接口参数不能为空");
    // 获取数据库中的银盛当前支付渠道配置
    YsePayConfigEntity ysePayConfig = ysePayConfigService.getConfigByMethod(YseMethodEnum.DIVISION);
    Validator.validateNotNull(ysePayConfig,
        String.format("银盛接口配置为空，接口方法:{%s}",YseMethodEnum.DIVISION.getMethod()));
    // 创建银盛参数
    String requestData = buildDivisionPayDto(payParamDto, ysePayConfig);
    String respStr = yseApiAdaptor.post(payParamDto.getChannelOutTradeNo(), requestData,
        YseMethodEnum.DIVISION.getGatewayUrl());
    return JSONObject.parseObject(respStr, DivisionRespDTO.class);
  }


  /**
   * 构建分账参数
   */
  private String buildDivisionPayDto(DivisionParamDTO payParamDto, YsePayConfigEntity ysePayConfig) {
    DivisionReqDTO businessParam = DivisionReqDTO.buildDivisionPublicRequestDTO(payParamDto,
        ysePayConfig);
    return YseUtil.mapToSortedString(BeanUtil.beanToMap(businessParam, true, true));
  }


}
